package com.hs.auth.action;
 
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.hs.auth.model.HsAccount;
import com.hs.auth.model.HsOrg;
import com.hs.auth.model.HsUserinfo;
import com.hs.auth.service.IUserService;
import com.hs.core.action.BaseAction;
import com.hs.core.db.DBMgr;
import com.hs.core.utils.MD5;
import com.hs.core.utils.PageParam;
import com.hs.core.utils.PageUtil;
@Controller  
public class UserController  extends BaseAction {
    /**
	 * 
	 */
	private static final long serialVersionUID = -354434172898440670L;
	private static final Logger logger = Logger.getLogger(UserController.class);
	private IUserService userService;
	 @Autowired  
	public void setUserService(IUserService userService) {
		this.userService = userService;
	}
	 
	 /**
	  * 新增用户
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/auth/userInfo.do", method = RequestMethod.GET)   
     public ModelAndView userInfo(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
         String uid = request.getParameter("uid");//是否存在此参数表明是新增还是修改
         if(StringUtils.isNotEmpty(uid)){
        	 HsAccount info = (HsAccount)userService.findByID(HsAccount.class, new Long(uid));
        	 modelMap.put("accObj", info);
         } 
         List orgList = userService.findList("select a  from HsOrg a where pid!=0");
         List roleList = userService.findList("select a  from HsRole a  ");
         if(null != uid){
        	 DBMgr dbo = DBMgr.getDbUtilInst(request.getSession().getServletContext());
        	 List userroleList=dbo.queryList("select roleid from Hs_Accrole a where a.accid=?", new Object[]{new Long(uid)});
        	 if(userroleList.size()>0){
        		 Map obj = (Map)userroleList.get(0);
        		 modelMap.put("userrole", obj.get("roleid")+"");
        	 }
        	 List hsorguser = DBMgr.getDbUtilInst().queryList("select to_char(orgid) as orgidstr from HS_ORGUSER where userid=?", new Object[]{uid});
             HsOrg orginfo = null;
             if(hsorguser.size()>0){
            	 Map data = (Map)hsorguser.get(0);
            	 String orgid = (String)data.get("orgidstr");
            	 orginfo = (HsOrg )this.userService.findByID(HsOrg.class, new Long(orgid));
            	 modelMap.put("orginfo", orginfo);
             	 
             }
         }
         
         modelMap.put("orgList", orgList);
         modelMap.put("roleList", roleList);
		 return new ModelAndView("common/auth/userInfo",modelMap);
		 
	 }
	 /**
	  * 用户保存操作
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/auth/saveUser.do", method = RequestMethod.POST)   
     public ModelAndView saveUser(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		 String uid = request.getParameter("loginid");//是否存在此参数表明是新增还是修改
		 String accid = request.getParameter("id");//是否存在此参数表明是新增还是修改
		 String userid = request.getParameter("userid");//是否存在此参数表明是新增还是修改
		 String username = request.getParameter("username");
		 String pwd = request.getParameter("pwd");
		 String shengri = request.getParameter("shengri");
		 String sex = request.getParameter("sex");
		 String phone = request.getParameter("phone");
		 String handphone = request.getParameter("handphone");
		 String zuigxl = request.getParameter("zuigxl");
		 String biyyx = request.getParameter("school");
		 String zhicheng = request.getParameter("zhicheng");
		 String email = request.getParameter("email");
		 String postnum = request.getParameter("postno"); 
		 String address = request.getParameter("postaddress");
		 String roleid = request.getParameter("roleid");
		 String orgidnum = request.getParameter("orgid");
		 
		 String cardnum = request.getParameter("cardnum");
		 
		 String cardtype = request.getParameter("cardtype");
		 
		 HsUserinfo info = null;
		 HsAccount  acc = null;
         logger.debug("accid:" + accid);
          
         if(StringUtils.isNotEmpty(userid)){
        	 info = (HsUserinfo)userService.findByID(HsUserinfo.class, new Long(userid));
        	 acc = (HsAccount)userService.findByID(HsAccount.class, new Long(userid));
         }else{
        	 info = new HsUserinfo();
        	 acc = new HsAccount();
        	 acc.setLoginid(uid);
         }
         if(null == acc.getLoginid() || "".equals(acc.getLoginid())){
        	 acc.setLoginid(uid);
         } 
         info.setAddress(address);
         //info.setUseage(shengri);
         info.setBirthday(shengri);
         info.setPhone(phone);
         info.setBiyeyx(biyyx);
         info.setEmail(email);
         info.setHandphone(handphone);
         info.setPostnum(postnum);
         info.setUsername(username);
         info.setCardnum(cardnum);
         //info.setCardtype(Long.parseLong(cardtype));
         info.setCreatedate(new Date());
         if(StringUtils.isNotEmpty(sex))
        	 info.setUsersex(new Long(sex));
         info.setZuigxl(zuigxl); 
         info.setIsuse(1l);
         //info.setZhicheng(new Long(zhicheng));
         
         
         userService.saveObject(info); 
         logger.debug("accid:" + accid);
         if(StringUtils.isNotEmpty(pwd))
        	 acc.setPassword(MD5.md5(pwd));
         acc.setStatus(1l); 
        
         acc.setUserinfo(info);
         acc.setCreatetime(new Date());
        
         acc.setId(info.getId());
         userService.saveObject(acc);
         DBMgr dbo = DBMgr.getDbUtilInst(request.getSession().getServletContext());
         dbo.update("delete from HS_ACCROLE where ACCID=?", new Object[]{acc.getId()});
         dbo.update("insert into HS_ACCROLE (id,roleid,accid) values(SEQ_HS_ACCROLE_ID.nextval,?,?)", new Object[]{roleid,acc.getId()});
         HsOrg orginfo = null;
         List hsorguser = dbo.queryList("select to_char(orgid) as orgidstr from HS_ORGUSER where userid=?", new Object[]{info.getId()});
         if(hsorguser.size()>0){
        	 Map data = (Map)hsorguser.get(0);
        	 String orgid = (String)data.get("orgidstr");
        	 
        	 dbo.update("delete from HS_ORGUSER where userid=? and orgid=?",new Object[]{info.getId(),orgid}); 
        	 
         }
         if(StringUtils.isNotEmpty(orgidnum)){
    		 dbo.update("insert into HS_ORGUSER(id,userid,orgid) values(seq_hs_orguser_id.nextval,?,?)",new Object[]{info.getId(),orgidnum});
    		 orginfo = (HsOrg )this.userService.findByID(HsOrg.class, new Long(orgidnum));
        	 modelMap.put("orginfo", orginfo);
         }
        
         modelMap.put("accObj", acc);
         modelMap.put("flag", "fresh");
         List roleList = userService.findList("select a  from HsRole a ");
         modelMap.put("roleList", roleList);
         return new ModelAndView("common/auth/userInfo",modelMap);  
		 
	 }
	 /**
	  * 用户管理首页
	  * @param request
	  * @param response
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	@RequestMapping("/auth/userFrame.do")   
	public ModelAndView userFrame(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException { 
		return new ModelAndView("common/auth/userFrame");  
	}
	/**
	  * 用户注册首页
	  * @param request
	  * @param response
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	@RequestMapping("/auth/userreg.do")   
	public ModelAndView userreg(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException { 
		return new ModelAndView("common/auth/reginfo");  
	}
	/**
	  * 用户注册保存
	  * @param request
	  * @param response
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	@RequestMapping("/auth/regsave.do")   
	public ModelAndView regsave(HttpServletRequest request,
			HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException { 
		String uid = request.getParameter("loginid");//是否存在此参数表明是新增还是修改
		 String accid = request.getParameter("id");//是否存在此参数表明是新增还是修改
		 String userid = request.getParameter("userid");//是否存在此参数表明是新增还是修改
		 String username = request.getParameter("username");
		 String pwd = request.getParameter("pwd");
		 String shengri = request.getParameter("shengri");
		 String sex = request.getParameter("sex");
		 String phone = request.getParameter("phone");
		 String handphone = request.getParameter("handphone");
		 String zuigxl = request.getParameter("zuigxl");
		 String biyyx = request.getParameter("school");
		 String zhicheng = request.getParameter("zhicheng");
		 String email = request.getParameter("email");
		 String postnum = request.getParameter("postno"); 
		 String address = request.getParameter("postaddress");
		 String roleid = request.getParameter("roleid");
 		 String cardnum = request.getParameter("cardnum"); 
		 String cardtype = request.getParameter("cardtype");
		 String xuewei = request.getParameter("xuewei"); 
		 String zhuanye = request.getParameter("zhuanye");
		 
		 HsUserinfo info = null;
		 HsAccount  acc = null;
        logger.debug("accid:" + accid);
        if(StringUtils.isNotEmpty(userid)){
       	 	info = (HsUserinfo)userService.findByID(HsUserinfo.class, new Long(userid));
       	 	acc = (HsAccount)userService.findByID(HsAccount.class, new Long(userid));
        }else{
            List userlist = this.getDbo(request).queryList("select to_char(id) as dbid from HS_USERINFO WHERE CARDTYPE=? AND CARDNUM=?", new Object[]{cardtype,cardnum});
            if(userlist.size() >0){
            	Map userobj = (Map)userlist.get(0);
            	String dbuserid = (String)userobj.get("dbid");
            	info = (HsUserinfo)userService.findByID(HsUserinfo.class, new Long(dbuserid));
           	 	acc = (HsAccount)userService.findByID(HsAccount.class, new Long(dbuserid)); 
            }else{ 
	       	 	info = new HsUserinfo();
	       	 	acc = new HsAccount();
	       	 	acc.setLoginid(uid);
            }
        }
        info.setAddress(address);
        //info.setUseage(shengri);
        info.setBirthday(shengri);
        info.setPhone(phone);
        info.setBiyeyx(biyyx);
        info.setEmail(email);
        info.setHandphone(handphone);
        info.setPostnum(postnum);
        info.setUsername(username);
        info.setCardnum(cardnum);
        info.setCardtype(Long.parseLong(cardtype));
        info.setCreatedate(new Date());
        info.setSpecialtype(zhuanye);
        info.setZuizhongxw(new Long(xuewei));
        if(StringUtils.isNotEmpty(sex))
       	 info.setUsersex(new Long(sex));
        info.setZuigxl(zuigxl); 
        info.setIsuse(1l);
        info.setZhicheng(new Long(zhicheng));
        
        
        userService.saveObject(info); 
        logger.debug("accid:" + accid);
        if(StringUtils.isNotEmpty(pwd))
       	 acc.setPassword(MD5.md5(pwd));
        acc.setStatus(1l); 
       
        acc.setUserinfo(info);
        acc.setCreatetime(new Date());
       
        acc.setId(info.getId());
        acc.setLoginid(uid);
        userService.saveObject(acc);
        DBMgr dbo = DBMgr.getDbUtilInst(request.getSession().getServletContext());
        dbo.update("delete from HS_ACCROLE where accid=?",new Object[]{acc.getId()});
        dbo.update("insert into HS_ACCROLE (id,roleid,accid) values(SEQ_HS_ACCROLE_ID.nextval,?,?)", new Object[]{1,acc.getId()});
         
        modelMap.put("accObj", acc);
        modelMap.put("flag", "fresh");
 		return new ModelAndView("common/auth/reginfo");  
	}
	 /**
	  * 用户列表
	  * @param request
	  * @param response
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	@RequestMapping("/auth/listUser.do")   
	public ModelAndView listUser(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException { 
		PageParam pageParam = new  PageParam(request,"auth/listUser.do");
		StringBuffer buffer = new StringBuffer(); 
	    
	    //排序结束
		PageUtil pageUtil = null;
		StringBuffer searchBuffer = new StringBuffer(" select a from HsAccount a where a.id!=1 and a.status=1 ");
		//StringBuffer searchBuffer = new StringBuffer(" select a from HbpZhu a where 1=1 ");
		
		String loginId = request.getParameter("loginId"); 
		String userName = request.getParameter("userName");  

		 
		if(StringUtils.isNotBlank(userName)){
			searchBuffer.append(" and a.userinfo.username like '%").append(userName).append("%'");
			pageParam.getConditionMap().put("userName", userName);
			request.setAttribute("userName", userName);
		}  
		if(StringUtils.isNotBlank(loginId)){
			searchBuffer.append(" and a.loginid ='").append(loginId).append("'");
			pageParam.getConditionMap().put("loginId", loginId);
			request.setAttribute("loginId", loginId);
		}  
		 
		 //searchBuffer.append(" order by a.loginid");
		Map data = new HashMap();
		pageParam.setSearchSql(searchBuffer.toString());
		pageUtil = userService.getAccList(pageParam);	
		data.put("dataList", pageUtil);   
 		return new ModelAndView("common/auth/userList",data);  
	}
	 
	 /**
	  * 修改用户信息
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/auth/modifyUserinfo.do")   
    public ModelAndView modifyUserinfo(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		 String uid = request.getParameter("uid");//是否存在此参数表明是新增还是修改
         if(StringUtils.isNotEmpty(uid)){
        	 HsAccount info = (HsAccount)userService.findByID(HsAccount.class, new Long(uid));
        	 modelMap.put("accObj", info);
         } 
         List orgList = userService.findList("select a  from HsOrg a where pid!=0");
         List roleList = userService.findList("select a  from HsRole a  ");
         if(null != uid){
        	 DBMgr dbo = DBMgr.getDbUtilInst(request.getSession().getServletContext());
        	 List userroleList=dbo.queryList("select roleid from Hs_Accrole a where a.accid=?", new Object[]{new Long(uid)});
        	 if(userroleList.size()>0){
        	 Map obj = (Map)userroleList.get(0);
        	 modelMap.put("userrole", obj.get("roleid")+"");
        	 }
         }
         modelMap.put("orgList", orgList);
         modelMap.put("roleList", roleList);
         return new ModelAndView("common/auth/modifyUserinfo",modelMap);
	 } 
	 /**
	  * 用户保存操作
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/auth/saveUserinfo.do", method = RequestMethod.POST)   
     public ModelAndView saveUserinfo(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		 String uid = request.getParameter("loginid");//是否存在此参数表明是新增还是修改
		 String accid = request.getParameter("id");//是否存在此参数表明是新增还是修改
		 String userid = request.getParameter("userid");//是否存在此参数表明是新增还是修改
		 String username = request.getParameter("username");
		 String pwd = request.getParameter("pwd");
		 String shengri = request.getParameter("shengri");
		 String sex = request.getParameter("sex");
		 String phone = request.getParameter("phone");
		 String handphone = request.getParameter("handphone");
		 String zuigxl = request.getParameter("zuigxl");
		 String biyyx = request.getParameter("school");
		 String zhicheng = request.getParameter("zhicheng");
		 String email = request.getParameter("email");
		 String postnum = request.getParameter("postno"); 
		 String address = request.getParameter("postaddress");
		 String roleid = request.getParameter("roleid");
 		 
		 HsUserinfo info = null;
		 HsAccount acc = null;
         logger.debug("accid:" + accid);
         if(StringUtils.isNotEmpty(accid)){
        	 acc = (HsAccount)userService.findByID(HsAccount.class, new Long(accid));
         }else{
        	 acc = new HsAccount();
        	 acc.setLoginid(uid);
         }
         if(StringUtils.isNotEmpty(userid)){
        	 info = (HsUserinfo)userService.findByID(HsUserinfo.class, new Long(userid));
         }else{
        	 info = new HsUserinfo();
         }
         logger.debug("accid:" + accid);
         if(StringUtils.isNotEmpty(pwd))
        	 acc.setPassword(MD5.md5(pwd));
         acc.setStatus(1l); 
        
         acc.setUserinfo(info);
         acc.setCreatetime(new Date());
         info.setAddress(address);
         //info.setUseage(shengri);
         info.setBirthday(shengri);
         info.setPhone(phone);
         info.setBiyeyx(biyyx);
         info.setEmail(email);
         info.setHandphone(handphone);
         info.setPostnum(postnum);
         info.setUsername(username);
         info.setCreatedate(new Date());
         if(StringUtils.isNotEmpty(sex))
        	 info.setUsersex(new Long(sex));
         info.setZuigxl(zuigxl); 
         info.setZhicheng(new Long(zhicheng));
         
         
         userService.saveObject(info); 
         userService.saveObject(acc);
         DBMgr dbo = DBMgr.getDbUtilInst(request.getSession().getServletContext());
       
         modelMap.put("accObj", acc);
         modelMap.put("flag", "fresh"); 
         return new ModelAndView("common/auth/modifyUserinfo",modelMap);  
		 
	 }
}
